<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Test;

use App\Controller\AbstractController;
use App\Job\TestJob;
use App\Request\Test\Exception\ExceptionRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;

use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Context;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use App\Service\QueueService;

/**
 *  Test Controller
 * @Controller(prefix="/test/index", server="http")
 * @package App\Controller\Test
 */
class IndexController extends AbstractController
{
    /**
     * @Inject()
     * @var QueueService
     */
    protected $queueService;

    /**
     * @RequestMapping(path="index", methods="get,post")
     * @return ResponseInterface
     */
    public function index()
    {

        $str = "56+78=\n578-897=\n98*786=\n8987600/50=";
//        $str = "7月30日，_中共中央政治局召开会议，分析研究了当前经济形势，部署下半年经济工作。近日，总台记者专访十位经济领域的部长，共话下半年中国经济工作打算怎么干。";

        $after = '';
        $result = '';
        $matchs = [];

        $after = preg_replace ("/([\d]+[\+\-\*\/][\d]+=)$/","$1？", $str);

//        $result = preg_match_all("/[\W]+/u", $str, $matchs);

        $result = preg_match_all("/^[\d]+[\+\-\*\/][\d]+=/m", $str, $matchs);

        return $this->success(['before' => $str, 'after' => $after, 'result' => $result, 'matchs' => $matchs]);
    }


    /**
     * @RequestMapping(path="exception", methods="get,post")
     * @param  ExceptionRequest  $request
     * @return ResponseInterface
     */
    public function exception(ExceptionRequest $request)
    {
        $exceptionName = $request->input('exception_name');

        $path = "\\App\\Exception\\";
        $class = $path.$exceptionName . 'Exception';

        // 异常存在 直接抛出异常
        if (class_exists($class)) {
            throw new $class('this is a ' . $exceptionName . 'Exception', random_int(0, 100));
        }

        return $this->error('exceptionName is not found.');
    }

    /**
     * @RequestMapping(path="queue", methods="get,post")
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function queue(RequestInterface $request)
    {
        $params = $request->all();

        echo date("Y-m-d H:i:s") . " queue request exec\r\n";
        $result = $this->queueService->push(new TestJob($params), 2);
        $this->queueService->testJob($params);

        return $this->success(['result' => $result]);
    }


}
